﻿using Aliyun.Acs.Core;
using Aliyun.Acs.Core.Auth.Sts;
using Aliyun.Acs.Core.Http;
using Aliyun.Acs.Core.Profile;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Text.Json;
using AntJoin.Redis;
using static Aliyun.Acs.Core.Auth.Sts.AssumeRoleResponse;

namespace AntJoin.Log
{
    public class STSLogin
    {
        public AssumeRole_Credentials GetSigninToken()
        {
            var stsToken = RedisHelper.GetValue("STSToken");
            if (string.IsNullOrEmpty(stsToken))
            {
                const string REGIONID = "cn-shenzhen";
                //const string ENDPOINT = "sts.cn-shenzhen.aliyuncs.com";
                // 构建一个阿里云client, 用于发起请求
                // 构建阿里云client时需要设置AccessKey ID和AccessKey Secret
                //DefaultProfile.AddEndpoint(REGIONID, REGIONID, "Sts", ENDPOINT, false);
                IClientProfile profile = DefaultProfile.GetProfile(REGIONID, "LTAI4FvwzkZEmXo7bPGVXEg5", "4Crk4yexurGAF43lsQomfSPteCG4Qf");
                DefaultAcsClient client = new DefaultAcsClient(profile);
                // 构建AssumeRole请求
                AssumeRoleRequest request = new AssumeRoleRequest();
                request.AcceptFormat = FormatType.JSON;
                // 指定角色ARN
                request.RoleArn = "acs:ram::1420096974371822:role/AliYunSTSRole";
                request.RoleSessionName = "alice";

                try
                {
                    AssumeRoleResponse response = client.GetAcsResponse(request);
                    //默认有效期3600秒
                    RedisHelper.SetValue("STSToken", JsonSerializer.Serialize(response.Credentials), TimeSpan.Parse(response.Credentials.Expiration));
                    return response.Credentials;
                }
                catch (Exception ex)
                {
                    LogHelper.Log(LogLevel.ERROR, "阿里云STS授权失败", ex);
                    return null;
                }
            }
            else
            {
                return JsonSerializer.Deserialize<AssumeRole_Credentials>(stsToken);
            }
        }

        /// <summary>
        /// 获取日志服务免密登录链接
        /// </summary>
        /// <param name="LoginUrl"></param>
        /// <param name="DestinationUrl"></param>
        /// <returns></returns>
        public string GetSignInUrl(string LoginUrl, string DestinationUrl)
        {
            var stsToken = GetSigninToken();
            string signInHost = "http://signin.aliyun.com";
            string signInTokenUrl = signInHost + string.Format(
                    "/federation?Action=GetSigninToken"
                    + "&AccessKeyId={0}"
                    + "&AccessKeySecret={1}"
                    + "&SecurityToken={2}&TicketType=mini",
                    System.Web.HttpUtility.UrlEncode(stsToken.AccessKeyId, Encoding.UTF8),
                    System.Web.HttpUtility.UrlEncode(stsToken.AccessKeySecret, Encoding.UTF8),
                    System.Web.HttpUtility.UrlEncode(stsToken.SecurityToken, Encoding.UTF8)
                    );
            var res = CreateGetHttpResponse(signInTokenUrl);
            if (res.StatusCode == HttpStatusCode.OK)
            {
                string resStr = GetResponseString(res);
                dynamic o = JsonSerializer.Deserialize<dynamic>(resStr);
                string token = o.SigninToken;
                var signInUrl = signInHost + string.Format(
                "/federation?Action=Login"
                + "&LoginUrl={0}"
                + "&Destination={1}"
                + "&SigninToken={2}",
                System.Web.HttpUtility.UrlEncode(LoginUrl, Encoding.UTF8),
                System.Web.HttpUtility.UrlEncode(DestinationUrl, Encoding.UTF8),
                System.Web.HttpUtility.UrlEncode(token, Encoding.UTF8));
                return signInUrl;
            }
            else
            {
                LogHelper.Log(LogLevel.ERROR, "阿里云STS角色登录失败");
                return null;
            }
        }

        public HttpWebResponse CreateGetHttpResponse(string url)
        {
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            request.Method = "GET";
            request.ContentType = "application/x-www-form-urlencoded";//链接类型
            return request.GetResponse() as HttpWebResponse;
        }

        public string GetResponseString(HttpWebResponse webresponse)
        {
            using (Stream s = webresponse.GetResponseStream())
            {
                StreamReader reader = new StreamReader(s, Encoding.UTF8);
                return reader.ReadToEnd();
            }
        }
    }
}
